<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="50%"
    top="60px"
  >
    <el-form
      style="height: 500px; overflow: auto; padding-right: 20px"
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      :label-width="$i18n.locale === 'en-US' ? '140px' : '140px'"
    >
      <!--<el-row v-if="activeName=='first'">-->

      <el-row>
        <el-col :span="12">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="dataForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="价格" prop="price">
            <el-input v-model="dataForm.price" type="number"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="折扣价" prop="discountPrice">
            <el-input v-model="dataForm.discountPrice" type="number"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="上下架" prop="status">
            <el-select v-model="dataForm.status" clearable style="width: 100%">
              <el-option label="上架" :value="0"> </el-option>
              <el-option label="下架" :value="1"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="套餐有效期" required>
            <!-- <el-date-picker
              style="width: 100%"
              v-model="value1"
              type="daterange"
              value-format="yyyy-MM-dd HH:mm"
              format="yyyy-MM-dd HH:mm"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            >
            </el-date-picker> -->
             <el-date-picker
              style="width: 100%"
              v-model="value1"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm"
              format="yyyy-MM-dd HH:mm"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上下架时间" required>
            <el-date-picker
              style="width: 100%"
              v-model="value2"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm"
              format="yyyy-MM-dd HH:mm"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <!--<el-col :span="12">-->
        <!--<el-form-item label="限制" prop="limitFlag">-->
        <!--<el-select-->
        <!--v-model="dataForm.limitFlag"-->
        <!--clearable-->
        <!--style="width: 100%"-->
        <!--&gt;-->
        <!--<el-option label="不限制" :value="1"> </el-option>-->
        <!--<el-option label="限制" :value="2"> </el-option>-->
        <!--</el-select>-->
        <!--</el-form-item>-->
        <!--</el-col>-->

        <el-col :span="12">
          <el-form-item label="退款说明" prop="refundRemark">
            <el-input v-model="dataForm.refundRemark"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="24"
          v-for="(item, index) in dataForm.noticeList"
          :key="index"
        >
          <el-form-item
            :label="`${'须知' + (index + 1)}`"
            :prop="'noticeList.' + index + '.notice'"
            :rules="{
              required: true,
              message: '请输入',
              trigger: 'blur',
            }"
          >
            <el-input
              v-model="item.notice"
              placeholder="格式如：周一至周日 10:30-20:30可用"
            ></el-input>
          </el-form-item>
          <el-form-item label="操作">
            <el-button
              type="danger"
              size="mini"
              @click="deleteNotice(item, index)"
              >删除须知</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="addNotice()"
              v-if="index == dataForm.noticeList.length - 1"
              >添加须知</el-button
            >
          </el-form-item>
        </el-col>

        <el-col
          :span="24"
          v-for="(item, index) in dataForm.useRuleList"
          :key="index"
        >
          <el-form-item
            :label="`${'使用规则' + (index + 1)}`"
            :prop="'useRuleList.' + index + '.useRule'"
            :rules="{
              required: true,
              message: '请输入',
              trigger: 'blur',
            }"
          >
            <el-input v-model="item.useRule"></el-input>
          </el-form-item>
          <el-form-item label="操作" prop="">
            <el-button
              type="danger"
              size="mini"
              @click="deleteUseRule(item, index)"
              >删除使用规则</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="addUseRule()"
              v-if="index == dataForm.useRuleList.length - 1"
              >添加使用规则</el-button
            >
          </el-form-item>
        </el-col>

        <el-col
          :span="24"
          v-for="(item, index) in dataForm.detail"
          :key="index"
        >
          <div class="detail">
            <el-form-item
              label="商品明细-名称"
              :prop="'detail.' + index + '.name'"
              :rules="{
                required: true,
                message: '请输入',
                trigger: 'blur',
              }"
            >
              <el-input v-model="item.name" style="width: 150px"></el-input>
            </el-form-item>
            <el-form-item
              label="商品明细-数量"
              :prop="'detail.' + index + '.number'"
              :rules="{
                required: true,
                message: '请输入',
                trigger: 'blur',
              }"
            >
              <el-input v-model="item.number" style="width: 150px"></el-input>
            </el-form-item>
            <el-form-item
              label="商品明细-价格"
              :prop="'detail.' + index + '.price'"
              :rules="{
                required: true,
                message: '请输入',
                trigger: 'blur',
              }"
            >
              <el-input v-model="item.price" style="width: 150px"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="操作" prop="">
            <el-button
              type="danger"
              size="mini"
              @click="deleteDays(item, index)"
              >删除明细</el-button
            >
            <el-button
              v-if="index == dataForm.detail.length - 1"
              type="primary"
              size="mini"
              @click="addDays()"
              >添加明细</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <p class="pdl60">
            <span style="color: #f44">*</span>商品封面<span
              >(支持png、jpg，建议尺寸750*980px，最多1张)</span
            >
          </p>
        </el-col>

        <el-col :span="24">
          <el-form-item label="" prop="coverImg">
             <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :on-success="successHandle"
              :before-upload="beforeUploadHandle"
            >
              <img v-if="dataForm.coverImg" :src="dataForm.coverImg" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <!-- <el-upload
              :action="url"
              :file-list="fileList"
              :limit="1"
              :before-upload="beforeUploadHandle"
              list-type="picture-card"
              :on-success="successHandle"
              :on-remove="handleRemove"
            >
              <i class="el-icon-plus"></i>
            </el-upload> -->
          </el-form-item>
        </el-col>
      </el-row>
      <!--<template v-if="activeName=='second'">-->
      <!--<editor-vue :content="dataForm.feature" @EditorChange="getEditor" ref="infoIntroduceRef"></editor-vue>-->
      <!--</template>-->
      <!-- <template v-if="activeName=='third'">
                <quill-editor class="ql-container" ref="myQuillEditor" v-model="dataForm.notice" />
            </template> -->
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
    <!-- 裁剪框 -->
    <cropper-dlg
      v-if="showCropper"
      :dialogVisible.sync="showCropper"
      :img-file="currentFile"
      ref="vueCropper"
      @upload="cropperUpload"
    ></cropper-dlg>
  </el-dialog>
</template>

<script>
import Cookies from "js-cookie";
import debounce from "lodash/debounce";
import editorVue from "@/components/editor";
import { join } from "lodash";
export default {
  data() {
    return {
      currentFile: "",
      cropperIndex: null,
      showCropper: false, //裁剪弹框
      isCropper: true, //上传之前是否显示裁剪
      fileList: [],
      url: `${
        window.SITE_CONFIG["apiURL"]
      }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
      dialogImageUrl: "",
      dialogVisible: false,
      visible: false,
      activeName: "first",
      //商品明细数组
      detail: [
        {
          name: "",
          number: "",
          price: "",
        },
      ],
      //商品须知数组

      //商品规则数组
      useRuleList: [
        {
          useRule: "",
        },
      ],
      value1: [],
      value2: [],
      dataForm: {
        useRuleList: [
          {
            useRule: "",
          },
        ],
        noticeList: [
          {
            notice: "",
          },
        ],
        //商品明细数组
        detail: [
          {
            name: "",
            number: "",
            price: "",
          },
        ],
        merchantId: "",
        id: "",
        name: "",
        price: "",
        status: 0,
        delFlag: 0,
        //  limitFlag:1,
        discountPrice: "",
        refundRemark: "",
        activityStartTime: "",
        activityEndTime: "",
        notice: "",
        useRule: "",
        coverImg: "",
        productsDetail: "",
        productOnTime: "",
        productOffTime: "",
      },
    };
  },
  computed: {
    dataRule() {
      return {
        name: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        price: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        discountPrice: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        coverImg: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        refundRemark: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  components: {
    editorVue,
  },
  watch: {
    value1(newval, oldval) {
      if (newval) {
        if (newval != oldval) {
          this.dataForm.activityStartTime = newval[0];
          this.dataForm.activityEndTime = newval[1];
        }
      } else {
        this.dataForm.activityStartTime = "";
        this.dataForm.activityEndTime = "";
      }
    },
    value2(newval, oldval) {
      if (newval) {
        if (newval != oldval) {
          this.dataForm.productOnTime = newval[0];
          this.dataForm.productOffTime = newval[1];
        }
      } else {
        this.dataForm.productOnTime = "";
        this.dataForm.productOffTime = "";
      }
    },
  },
  created() {},
  methods: {
    getEditor(val) {
      this.dataForm.information = val;
    },
    dealDate(date, type) {
      let str = "";
      let d = new Date(date);
      let year = d.getFullYear();
      let month = d.getMonth() + 1;
      let day = d.getDate();
      let h = d.getHours();
      let m = d.getMinutes();
      let s = d.getSeconds();
      if (type == 1)
        str =
          year +
          "-" +
          this.buLing(month) +
          "-" +
          this.buLing(day) +
          " " +
          this.buLing(h) +
          ":" +
          this.buLing(m) +
          ":" +
          this.buLing(s);
      else str = str = year + "-" + this.buLing(month) + "-" + this.buLing(day);
      return str;
    },
    buLing(data) {
      let str = data;
      if (data < 10) str = "0" + data;
      return str;
    },
    //添加明细
    addDays() {
      this.dataForm.detail.push({
        name: "",
        number: "",
        price: "",
      });
    },
    //删除明细
    deleteDays(e, index) {
      if (this.dataForm.detail.length > 1) {
        this.dataForm.detail.splice(index, 1);
      }
    },
    //添加须知
    addNotice() {
      // this.dataForm.noticeList.push({
      //   notice: "",
      // });
      this.$set(this.dataForm.noticeList, this.dataForm.noticeList.length, {
        notice: "",
      });
    },
    //删除须知
    deleteNotice(e, index) {
      if (this.dataForm.noticeList.length > 1) {
        this.dataForm.noticeList.splice(index, 1);
      }
    },
    //添加使用规则
    addUseRule() {
      this.dataForm.useRuleList.push({
        useRule: "",
      });
    },
    //删除使用规则
    deleteUseRule(e, index) {
      if (this.dataForm.useRuleList.length > 1) {
        this.dataForm.useRuleList.splice(index, 1);
      }
    },

    handleRemove(file, fileList) {
      this.fileList = fileList.map((item) => {
        return item;
      });
    },
    // 上传之前
    beforeUploadHandle(file) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error(
          this.$t("upload.tip", {
            format: "jpg、png、gif",
          })
        );
        return false;
      }
      if (this.isCropper) {
        //显示裁剪
        this.currentFile = file;
        // this.cropperIndex = name;
        this.showCropper = true;
        this.$nextTick(() => {
          this.$refs.vueCropper.init();
        });
        return false;
      }
    },
    cropperUpload(data) {
      this.showCropper = false;
      if (data != "close") {
        //裁剪成功后获取的图片
        this.$http.post("/oss/file/aliyunUpload", data).then((res) => {
          if (res.data.code == 0) {
            this.successHandle(res.data);
          }
        });
      }
    },
    // 上传成功
    successHandle(res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.dataForm.coverImg = res.data.url;
      // this.fileList.push({
      //   name: "",
      //   url: res.data.url,
      // });
      // this.dataForm.coverImg = this.fileList
      //   .map((item) => {
      //     return item.url;
      //   })
      //   .toString();
    },
    init() {
      this.visible = true;
      this.fileList = [];
      this.value1 = [];
      this.value2 = [];
      this.dataForm.detail = [
        {
          name: "",
          number: "",
          price: "",
        },
      ];
      this.dataForm.useRuleList = [
        {
          useRule: "",
        },
      ];
      this.dataForm.noticeList = [
        {
          notice: "",
        },
      ];
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.getInfo();
        }
      });
    },
    // 获取信息
    getInfo() {
      this.$http
        .get("/scenic/merchant/product/" + this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = res.data;
          let picArr = this.dataForm.coverImg.split(",");
          for (let i = 0; i < picArr.length; i++) {
            this.fileList.push({
              url: picArr[i],
            });
          }

          // this.dataForm.useRuleList = JSON.parse(this.dataForm.useRule);
          this.$set(
            this.dataForm,
            "useRuleList",
            JSON.parse(this.dataForm.useRule)
          );
          // this.dataForm.noticeList = JSON.parse(this.dataForm.notice);
          this.$set(
            this.dataForm,
            "noticeList",
            JSON.parse(this.dataForm.notice)
          );
          // this.dataForm.typeArr = this.dataForm.type.split(',')
          this.value1 = [res.data.activityStartTime, res.data.activityEndTime];
          this.value2 = [res.data.productOnTime, res.data.productOffTime];

          if (this.dataForm.productsDetail != "") {
            // this.dataForm.detail = JSON.parse(this.dataForm.productsDetail);
            this.$set(
              this.dataForm,
              "detail",
              JSON.parse(this.dataForm.productsDetail)
            );
          } else {
            this.dataForm.detail = [
              {
                name: "",
                number: "",
                price: "",
              },
            ];
          }
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.dataForm.productsDetail = JSON.stringify(this.dataForm.detail);
        this.dataForm.useRule = JSON.stringify(this.dataForm.useRuleList);
        this.dataForm.notice = JSON.stringify(this.dataForm.noticeList);
        this.dataForm.merchantId = this.$store.state.user.MerchantId;
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          let picArr = [];
          this.fileList.filter((item) => {
            picArr.push(item.url);
          });
          this.dataForm.coverImgList=this.dataForm.coverImgList?this.dataForm.coverImgList:[];
          // this.dataForm.coverImg = picArr.join(",");
          this.$http[!this.dataForm.id ? "post" : "put"](
            "/scenic/merchant/product",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      {
        leading: true,
        trailing: false,
      }
    ),
  },
};
</script>

<style lang="scss" scoped>
.detail {
  display: flex;
}
h3 {
  padding: 30px 0 15px;
  width: 94%;
  margin: 0 auto 30px;
  border-bottom: 1px solid #ddd;
  color: #303133;
  font-size: 22px;
  overflow: hidden;
}

.aui-content .ql-container {
  height: auto;
}

.ql-container.ql-snow {
  height: 500px;
}

.rooms .item {
  display: inline-block;
  margin-right: 15px;
  position: relative;

  .el-icon-error {
    position: absolute;
    right: 6px;
    top: -6px;
    font-size: 20px;
    color: #dd0606;
  }
}
</style>
